<template>
    <div >
        <el-container>
            <el-main   class="loginbg">
                <div class="materialContainer " >
                    <div class="box">
                        <el-form ref="registerFormRef" v-if="isLogin" :model="registerForm" :rules="registerRules" >
                            <div class="title" v-if="isLogin">注册</div>
                            <el-form-item @submit.prevent="submitRegisterForm" prop="username" class="input">
                                    <label for="regname" :style="usernameLabelStyles">用户名</label>
                                    <input
                                            v-model="registerForm.username"
                                            type="text"
                                            name="regname"
                                            id="regname"
                                            @focus="usernameOnFocus"
                                            @blur="usernameOnBlur"
                                    >
                                    <span class="spin" :style="{ width: usernameSpinWidth }"></span>
                            </el-form-item>

                            <el-form-item prop="userpass" class="input">
                                    <label for="regpass" :style="userpassLabelStyles">密码</label>
                                    <input
                                            v-model="registerForm.userpass"
                                            type="password"
                                            name="regpass"
                                            id="regpass"
                                            @focus="userpassOnFocus"
                                            @blur="userpassOnBlur"
                                    >
                                    <span class="spin" :style="{ width: userpassSpinWidth }"></span>

                            </el-form-item>


                            <!-- 确认密码输入框 -->
                            <el-form-item prop="confirmPass" class="input">
                                <label for="confirmpass" :style="confirmPassLabelStyles">确认密码</label>
                                <input
                                        v-model="registerForm.confirmPass"
                                        type="password"
                                        name="confirmpass"
                                        id="confirmpass"
                                        @focus="confirmPassOnFocus"
                                        @blur="confirmPassOnBlur"
                                >
                                <span class="spin" :style="{ width: confirmPassSpinWidth }"></span>
                            </el-form-item>
<!--                            email 输入框-->
                            <el-form-item prop="email" class="input">
                                <label for="email" :style="emailLabelStyles">邮箱</label>
                                <input
                                        v-model="registerForm.email"
                                        type="text"
                                        name="email"
                                        id="email"
                                        @focus="emailOnFocus"
                                        @blur="emailOnBlur"
                                >
                                <span class="spin" :style="{ width: emailSpinWidth }"></span>
                            </el-form-item>

                            <el-form-item  class="button register">
                                    <button  @click="submitRegisterForm">
                                        <span>注册</span>
<!--                                        <i class="fa fa-check"></i>-->
                                    </button>

                            </el-form-item>
                            <!--  -->
                        </el-form>
                    </div>
                    <div class="overbox">
                        <div
                                class="material-button-re alt-1"
                                @click="toLogin"
                        >
                            <span class="shape" ></span>
                        </div>
                    </div>
                </div>

            </el-main>
        </el-container>

    </div>
</template>

<script setup>
    import { reactive, ref,computed } from 'vue'
    import { ElMessage } from 'element-plus'
    import { useRouter } from "vue-router"
    import request from '../utlis/axios.js'
    const router = useRouter()
    const registerFormRef = ref()
    const isLogin = ref(true)

    //  注册信息
    const registerForm = reactive({
        username: '',
        userpass: '',
        confirmPass: '',
        email: '',
    })

    //用于用户名的悬浮样式
    const usernameIsFocused = ref(false);
    const usernameSpinWidth = ref('0px');
    const usernameLabelStyles = computed(() => ({
        lineHeight: usernameIsFocused.value || registerForm.username ? '18px' : '60px',
        fontSize: usernameIsFocused.value || registerForm.username ? '18px' : '24px',
        fontWeight: usernameIsFocused.value || registerForm.username ? '100' : '300',
        top: usernameIsFocused.value || registerForm.username ? '0px' : '10px',
    }));
    // 用户名输入框获取焦点时的处理
    function usernameOnFocus() {
        usernameIsFocused.value = true;
        usernameSpinWidth.value = '100%';
    }
    // 用户名输入框失去焦点时的处理
    function usernameOnBlur() {
        usernameIsFocused.value = false;
        usernameSpinWidth.value = '0px';
        if (!registerForm.username) {
            // 只有当用户名为空时更新样式
            usernameLabelStyles.value = {
                lineHeight: '60px',
                fontSize: '24px',
                fontWeight: '300',
                top: '10px',
            };
        }
        if (!validateAndShowMessage('username', registerRules.username)) {
            // 如果验证失败，可以在这里阻止表单提交或做其他处理
        }

    }
    // 用于密码的悬浮样式
    const userpassIsFocused = ref(false);
    const userpassSpinWidth = ref('0px');
    const userpassLabelStyles = computed(() => ({
        lineHeight: userpassIsFocused.value || registerForm.userpass ? '18px' : '60px',
        fontSize: userpassIsFocused.value || registerForm.userpass ? '18px' : '24px',
        fontWeight: userpassIsFocused.value || registerForm.userpass ? '100' : '300',
        top: userpassIsFocused.value || registerForm.userpass ? '0px' : '10px',
    }));
    // 密码输入框获取焦点时的处理
    function userpassOnFocus() {
        userpassIsFocused.value = true;
        userpassSpinWidth.value = '100%';
    }
    // 密码输入框失去焦点时的处理
    function userpassOnBlur() {
        userpassIsFocused.value = false;
        userpassSpinWidth.value = '0px';
        if (!registerForm.userpass) {
            // 只有当密码为空时更新样式
            userpassLabelStyles.value = {
                lineHeight: '60px',
                fontSize: '24px',
                fontWeight: '300',
                top: '10px',
            };
        }
        if (!validateAndShowMessage('userpass', registerRules.userpass)) {
            // 如果验证失败，可以在这里阻止表单提交或做其他处理
        }
    }
    // 用于确认密码的悬浮样式
    const confirmPassIsFocused = ref(false);
    const confirmPassSpinWidth = ref('0px');
    const confirmPassLabelStyles = computed(() => ({
        lineHeight: confirmPassIsFocused.value || registerForm.confirmPass ? '18px' : '60px',
        fontSize: confirmPassIsFocused.value || registerForm.confirmPass ? '18px' : '24px',
        fontWeight: confirmPassIsFocused.value || registerForm.confirmPass ? '100' : '300',
        top: confirmPassIsFocused.value || registerForm.confirmPass ? '0px' : '10px',
    }));
    // 确认密码输入框获取焦点时的处理
    function confirmPassOnFocus() {
        confirmPassIsFocused.value = true;
        confirmPassSpinWidth.value = '100%';
    }
    // 确认密码输入框失去焦点时的处理
    function confirmPassOnBlur() {
        confirmPassIsFocused.value = false;
        confirmPassSpinWidth.value = '0px';
        if (!registerForm.confirmPass) {
            // 只有当确认密码为空时更新样式
        }
        if (!validateAndShowMessage('confirmPass', registerRules.confirmPass)) {
            // 如果验证失败，可以在这里阻止表单提交或做其他处理
        }
    }
    //email
    const emailIsFocused = ref(false);
    const emailSpinWidth = ref('0px');
    const emailLabelStyles = computed(() => ({
        lineHeight: emailIsFocused.value || registerForm.email ? '18px' : '60px',
        fontSize: emailIsFocused.value || registerForm.email ? '18px' : '24px',
        fontWeight: emailIsFocused.value || registerForm.email ? '100' : '300',
        top: emailIsFocused.value || registerForm.email ? '0px' : '10px',
    }));
    // 邮箱输入框获取焦点时的处理
    function emailOnFocus() {
        emailIsFocused.value = true;
        emailSpinWidth.value = '100%';
    }
    // 邮箱输入框失去焦点时的处理
    function emailOnBlur() {
        emailIsFocused.value = false;
        emailSpinWidth.value = '0px';
        if (!registerForm.email) {
            // 只有当邮箱为空时更新样式
            emailLabelStyles.value = {
                lineHeight: '60px',
                fontSize: '24px',
                fontWeight: '300',
                top: '10px',
            };
        }
        if (!validateAndShowMessage('email', registerRules.email)) {

        }
    }

    //去登陆页面
    const toLogin = () => {
        //    跳转到注册页面
        router.push('/login')
    }

    //注册校验规则
    // 定义一个函数来根据规则检查并显示错误消息
    function validateAndShowMessage(fieldName, rules) {
        const fieldValue = registerForm[fieldName];
        const failedRules = rules.filter(rule => {
            if (rule.required && !fieldValue) {
                return true;
            }
            if (rule.min !== undefined && fieldValue.length < rule.min) {
                return true;
            }
            if (rule.max !== undefined && fieldValue.length > rule.max) {
                return true;
            }
            return false;
        });

        if (failedRules.length > 0) {
            // 组合所有失败规则的消息
            const errorMessage = failedRules.map(rule => rule.message).join('，');
            ElMessage({
                message: `请注意！${errorMessage}`,
                type: 'error',
                duration: 5000,
            });

            return false; // 表示验证未通过
        }
        return true; // 验证通过
    }
    const registerRules = reactive({
        username: [
            { required: true, message: '用户名不可为空', trigger: 'blur' },
            { pattern: /^[a-zA-Z0-9_]{3,20}$/, message: '账号名称需为3-20位的字母、数字或下划线', trigger: 'blur'  },
        ],
        userpass: [
            { required: true, message: '密码不可为空', trigger: 'blur' },
            { pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[A-Za-z\d]{6,20}$/,
              message: '密码需包含至少1个小写字母、1个大写字母、1个数字长度6-20',
              trigger: 'blur' },
        ],
        confirmPass: [
            { required: true, message: '确认密码不可为空', trigger: 'blur' },
            { validator: (rule, value, callback) => {
                    if (value !== registerForm.userpass) {
                        callback(new Error('两次输入的密码不一致'))
                    } else {
                        callback()
                    }
                }, trigger: 'blur' }
        ],
        email: [
            { required: true, message: '邮箱不可为空', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] },
        ],
    })

    //    注册请求处理
    const submitRegisterForm = (event) => {
        registerFormRef.value.validate((valid) => {
            event.preventDefault(); // 阻止表单默认提交行为
            //valid：对表单进行校验
            if (valid) {
                request({
                    url: '/register',
                    method: 'POST',
                    data: registerForm
                }).then(res => {
                    if (200 == res.data.errorCode) {
                        ElMessage({
                            message: '注册成功！',
                            type: 'success',
                        })
                        router.push('/login')
                    } else {
                        ElMessage({
                            message: '用户名或邮箱已存在！',
                            type: 'error',
                        })
                    }
                })
            } else {
                ElMessage({
                    message: '账号或者密码格式错误！',
                    type: 'error',
                })
            }
        })
    }

</script>

<style lang="scss" scoped>
  @import '/src/assets/css/font-awesome-4.7.0/css/font-awesome.min.css';
  @import '/src/assets/css/style.css';


</style>



